<template>
  <div class="container mx-auto px-4 py-8">
    <!-- 页面标题 -->
    <div class="mb-8">
      <h1 class="text-3xl font-bold text-white">
        {{ categoryTitle }}
      </h1>
    </div>

    <!-- 筛选条件 -->
    <el-card class="mb-8 filter-card">
      <!-- 类型筛选 -->
      <div class="flex flex-wrap items-center gap-4 mb-4">
        <span class="text-gray-300 min-w-[60px]">类型：</span>
        <el-button
          v-for="genre in genres"
          :key="genre.columnId"
          :type="selectedGenre === genre.columnId ? 'primary' : 'default'"
          size="small"
          @click="selectedGenre = genre.columnId"
        >
          {{ genre.name }}
        </el-button>
      </div>

      <!-- 年份筛选 -->
      <div class="flex flex-wrap items-center gap-4 mb-4">
        <span class="text-gray-300 min-w-[60px]">年份：</span>
        <el-button
          v-for="year in years"
          :key="year"
          :type="selectedYear === year ? 'primary' : 'default'"
          size="small"
          @click="selectedYear = year"
        >
          {{ year }}
        </el-button>
      </div>

      <!-- 地区筛选 -->
      <div class="flex flex-wrap items-center gap-4 mb-4">
        <span class="text-gray-300 min-w-[60px]">地区：</span>
        <el-button
          v-for="country in countries"
          :key="country"
          :type="selectedCountry === country ? 'primary' : 'default'"
          size="small"
          @click="selectedCountry = country"
        >
          {{ country }}
        </el-button>
      </div>

      <!-- 排序方式 -->
      <div class="flex flex-wrap items-center gap-4">
        <span class="text-gray-300 min-w-[60px]">排序：</span>
        <el-button
          v-for="sort in sortOptions"
          :key="sort.value"
          :type="selectedSort === sort.value ? 'primary' : 'default'"
          size="small"
          @click="selectedSort = sort.value"
        >
          {{ sort.label }}
        </el-button>
      </div>
    </el-card>

    <!-- 影片列表 -->
    <div v-if="pending" class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
      <el-skeleton v-for="i in 12" :key="i" :rows="0" animated class="h-80">
        <template #template>
          <el-skeleton-item variant="image" class="w-full h-64" />
          <el-skeleton-item variant="text" class="mt-2" />
          <el-skeleton-item variant="text" style="width: 60%" />
        </template>
      </el-skeleton>
    </div>

    <div v-else-if="movies && movies.length > 0" class="grid grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
      <MovieCard
        v-for="movie in movies"
        :key="movie.movieBasicsId"
        :movie="movie"
      />
    </div>

    <el-empty v-else description="暂无相关影片" />

    <!-- 分页 -->
    <div v-if="total > pageSize" class="mt-8 flex justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 36, 48]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
const route = useRoute()

// 获取栏目值
const columnValue = computed(() => route.params.columnValue as string)

// 分类标题映射
const categoryTitleMap: Record<string, string> = {
  'movie': '电影',
  'tv': '电视剧',
  'anime': '动漫',
  'variety': '综艺',
  'documentary': '纪录片'
}

const categoryTitle = computed(() => categoryTitleMap[columnValue.value] || '影视')

// 筛选条件
const selectedGenre = ref('全部')
const selectedYear = ref('全部')
const selectedCountry = ref('全部')
const selectedSort = ref('latest')

// 筛选选项（动态加载）
const genres = ref<string[]>(['全部'])
const years = ref<string[]>(['全部'])
const countries = ref<string[]>(['全部'])
const sortOptions = [
  { label: '最新上映', value: 'latest' },
  { label: '最热门', value: 'hottest' },
  { label: '评分最高', value: 'rating' }
]

// 加载筛选条件选项
const filterOptionsLoading = ref(false)
const loadFilterOptions = async () => {
  filterOptionsLoading.value = true
  try {
    const data: any = await $fetch('/dev-api/app/movieapp/filter-options', {
      params: { columnValue: columnValue.value }
    })
    if (data && data.code === 200) {
      const result = data.data
      // 加载类型/标签
      if (result.tags && result.tags.length > 0) {
        genres.value = [{columnId:'全部',name:'全部'}, ...result.tags]
      }
      // 加载年份（限制显示前20个）
      if (result.years && result.years.length > 0) {
        const yearList = result.years.slice(0, 20).map((y: number) => String(y))
        years.value = ['全部', ...yearList]
      }
      // 加载地区
      if (result.areas && result.areas.length > 0) {
        countries.value = ['全部', ...result.areas]
      }
    }
  } catch (error) {
    console.error('获取筛选条件失败:', error)
    // 保留默认的"全部"选项
    genres.value = ['全部']
    years.value = ['全部']
    countries.value = ['全部']
  } finally {
    filterOptionsLoading.value = false
  }
}

// 分页
const currentPage = ref(1)
const pageSize = ref(24)
const total = ref(0)
const movies = ref<any[]>([])
const pending = ref(false)

// 获取影片列表
const getMovieList = async () => {
  pending.value = true
  try {
    const params: any = {
      searchValue: columnValue.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: '0'
    }

    // 添加筛选条件（匹配后端字段名）
    if (selectedGenre.value !== '全部') {
      params.columnValue = selectedGenre.value
    }
    if (selectedYear.value !== '全部') {
      params.year = parseInt(selectedYear.value)
    }
    if (selectedCountry.value !== '全部') {
      params.area = selectedCountry.value
    }

    const data: any = await $fetch('/dev-api/app/movieapp/list', {
      params
    })

    // /app/** 接口返回 {rows: [], total: number} 格式
    movies.value = data.rows || []
    total.value = data.total || 0
  } catch (error) {
    console.error('获取影片列表失败:', error)
    movies.value = []
    total.value = 0
  } finally {
    pending.value = false
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  getMovieList()
}

const handlePageChange = (val: number) => {
  currentPage.value = val
  getMovieList()
}

// 监听筛选条件变化，重置页码
watch([selectedGenre, selectedYear, selectedCountry, selectedSort], () => {
  currentPage.value = 1
  getMovieList()
})

// 监听路由参数变化
watch(() => route.params.columnValue, () => {
  currentPage.value = 1
  selectedGenre.value = '全部'
  selectedYear.value = '全部'
  selectedCountry.value = '全部'
  selectedSort.value = 'latest'
  loadFilterOptions()
  getMovieList()
})

onMounted(() => {
  loadFilterOptions()
  getMovieList()
})

// SEO设置
useSeoMeta({
  title: categoryTitle.value,
  description: `${categoryTitle.value} - 最新最全的${categoryTitle.value}在线观看`,
})
</script>

<style scoped>
.filter-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-button--default) {
  background-color: transparent;
  border-color: rgba(55, 65, 81, 0.5);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-button--default:hover) {
  background-color: rgba(55, 65, 81, 0.3);
  border-color: #409EFF;
  color: #409EFF;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: transparent;
  --el-pagination-text-color: rgba(255, 255, 255, 0.8);
  --el-pagination-button-disabled-bg-color: rgba(31, 41, 55, 0.5);
  --el-pagination-button-disabled-color: rgba(255, 255, 255, 0.3);
  --el-pagination-hover-color: #409EFF;
}

:deep(.el-empty__description) {
  color: rgba(255, 255, 255, 0.6);
}
</style>
